const handler = require('sv-handler')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 题库列表
  async libList() {
    let {
      lib_id,
      lib_name,
      profession,
      vip,
      pagesize = 20,
      pagenum = 1
    } = this.params

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let libRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    const tempProfessionDB = dbJQL.collection('sv-exam-professions').field('profession_id, profession_name')
      .getTemp()

    // 连接表实例
    let query = dbJQL.collection('sv-exam-libs', tempProfessionDB)

    // 构建筛选条件(对象形式)
    const conditions = {}
    if (lib_id) {
      conditions.lib_id = dbCmd.eq(lib_id)
    }
    if (lib_name) {
      conditions.lib_name = dbCmd.eq(lib_name)
    }
    if (profession) {
      conditions["profession.0.profession_id"] = dbCmd.eq(profession)
    }
    if (vip || vip === 0) {
      conditions.vip = dbCmd.eq(vip)
    }
    // 将所有有效的筛选条件添加到查询对象中
    if (Object.keys(conditions).length > 0) {
      query = query.where(conditions)
    }

    if (pagesize < 1) {
      // 全量查询
      libRes = await query.get({
        getCount: true
      })
      total = libRes.count
      pages = 1
    } else {
      // 分页查询
      libRes = await query.skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })
      total = libRes.count
      pages = Math.ceil(total / pagesize)
    }

    return handler.result({
      data: libRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params
    })
  },
  // 更新题库
  async libUpdate() {
    const {
      _id,
      lib_id,
      lib_name
    } = this.params

    if (!lib_id || !lib_name) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const libRes = await db.collection('sv-exam-libs').doc(_id).update(this.params)

    return handler.result({
      data: libRes,
    })
  },
  // 添加题库
  async libAdd() {
    const {
      lib_id,
      lib_name
    } = this.params

    if (!lib_id || !lib_name) {
      throw handler.result({
        code: 40001
      })
    }

    const libRes = await db.collection('sv-exam-libs').add(this.params)

    return handler.result({
      data: libRes,
    })
  },
  // 删除题库
  async libDelete() {
    const {
      lib_id
    } = this.params

    if (!lib_id) {
      throw handler.result({
        code: 40001
      })
    }

    const libRes = await db.collection('sv-exam-libs').where({
      "lib_id": Array.isArray(lib_id) ? dbCmd.in(lib_id) : dbCmd.eq(lib_id)
    }).remove()

    return handler.result({
      data: libRes,
    })
  },
}